<?php

namespace Sharks\Core\Http\Routing;

use Closure;
use Sharks\Core\Http\Request;

/**
 * Form Csrf 中间件
 * 自动判断所有POST提交是否有正确的CSRF验证域
 */
class FormCsrfMiddleWare implements MiddleWare {

    function handle(Request $request, Closure $next) {

        if ($request->isPost()) {
            $csrfNaming = '_csrf';
            if ($request->input->has($csrfNaming) 
                && $request->app()->flash()->has($csrfNaming)
                && $request->input($csrfNaming) == $request->app()->flash()->get($csrfNaming)) {
                return $next($request);
            }
            elseif ($request->isAjax()){
                // throw new CsrfInvalidException();
                // or if is a josn request
                $request->app()->response()->status(400);
                return json(array('error' => 'CSRF-INVALID', 'msg' => 'Csrf Invalid'));
            }
            else {
                return status(400, 'CSRF INVALID');
            }
        }

        return $next($request);
    }
}